package com.uikoo9.plugin;

import com.jfinal.log.Logger;
import com.jfinal.plugin.IPlugin;
import com.uikoo9.manage.y.model.YJobModel;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

public class QuartzPlugin1 implements IPlugin {

    private final Logger logger = Logger.getLogger(getClass());

    private static final String JOB = "job";

    private String config = "job.properties";

    private Properties properties;

    public QuartzPlugin1(String config) {
        this.config = config;
    }

    public QuartzPlugin1() {
    }

    private SchedulerFactory schedulerFactory;
    private Scheduler scheduler;

    @SuppressWarnings("unchecked")
    public boolean start() {
        try {
            loadProperties();
        } catch (IOException e) {
            logger.error(e.getMessage());
            return false;
        }

        if (properties == null) {
            return false;
        }

        schedulerFactory = new StdSchedulerFactory();

        try {
            scheduler = schedulerFactory.getScheduler();
        } catch (SchedulerException e) {
            logger.error(e.getMessage());
            return false;
        }

        if (scheduler == null) {
            logger.error("scheduler is null");
            return false;
        }

        Enumeration<Object> enums = properties.keys();
        while (enums.hasMoreElements()) {
            String key = enums.nextElement() + "";
            if (!key.endsWith(JOB) || !isTrue(getJobKey(key, "enable"))) {
                continue;
            }

            String jobClassName = properties.get(key) + "";
            String jobName = key.substring(0, key.lastIndexOf("."));
            String jobCronExp = properties.getProperty(getJobKey(key, "cron")) + "";
            String jobGroup = properties.getProperty(getJobKey(key, "group", "jobGroup1"));
            String description = properties.getProperty(getJobKey(key, "description")) + "";

            Class<? extends Job> jobClass = null;
            try {
                jobClass = (Class<? extends Job>) Class.forName(jobClassName);
            } catch (ClassNotFoundException e) {
                logger.error(e.getMessage());
                return false;
            }

            JobDetail job = JobBuilder.newJob(jobClass)
                    .withIdentity(jobName, jobGroup).withDescription(description).build();
            CronTrigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity("trigger", jobGroup)
                    .withSchedule(
                            CronScheduleBuilder.cronSchedule(jobCronExp))
                    .build();

            try {
                scheduler.scheduleJob(job, trigger);
                scheduler.start();
            } catch (SchedulerException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                return false;
            }
        }

        return true;
    }

    public boolean stop() {

        try {
            scheduler.shutdown();
        } catch (SchedulerException e) {
            logger.error(e.getMessage());
            return false;
        }

        return true;
    }

    private void loadProperties() throws IOException {
        properties = new Properties();
        InputStream is = QuartzPlugin1.class.getClassLoader()
                .getResourceAsStream(config);
        properties.load(is);

        List<YJobModel> list = YJobModel.dao.findAll();
        for(YJobModel jm:list){
            properties.put(jm.getStr("y_job_group") +".job",jm.getStr("y_job_job") );
            properties.put(jm.getStr("y_job_group") +".cron",jm.getStr("y_job_cron"));
            properties.put(jm.getStr("y_job_group") +".enable",jm.getInt("y_job_enable")==1);
            properties.put(jm.getStr("y_job_group") +".group",jm.getStr("y_job_group"));
            properties.put(jm.getStr("y_job_group") +".description",jm.getStr("y_job_remark"));
        }

    }


    private String getJobKey(String str, String type, String defaultValue) {
        String key = getJobKey(str, type);

        if (key == null || "".equals(key.trim()))
            return defaultValue;

        return key;

    }

    private String getJobKey(String str, String type) {
        return str.substring(0, str.lastIndexOf(JOB)) + type;
    }

    private boolean isTrue(String key) {
        Object enable = properties.get(key);
        if (enable != null && "false".equalsIgnoreCase((enable + "").trim())) {
            return false;
        }
        return true;
    }

}